<template>
    <div class="main user-layout-register">
        <h3>用户注册</h3>
        <a-form-model ref="ruleForm" :model="form" :rules="rules" id="formRegister">

            <a-form-model-item prop="userRole">
                <a-select v-model="form.userRole" placeholder="选择用户类型">
                    <template v-for="(item,index) in roleList">
                        <a-select-option :value="item.value">
                            {{item.label}}
                        </a-select-option>
                    </template>
                </a-select>
            </a-form-model-item>

            <!--            <a-form-model-item prop="department" v-if="showSelectDepart">-->
            <!--                <j-select-depart v-model="form.department" :trigger-change="true"-->
            <!--                                 :searchParams="searchParams"-->
            <!--                                 :multi="false"></j-select-depart>-->
            <!--            </a-form-model-item>-->

            <a-form-item>
                <span style="margin-right: 8px;">是否是负责人？：<a-switch v-model="form.isPrincipal"/></span>
            </a-form-item>

            <!-- 省市县级联 -->
            <a-form-model-item prop="areaLinkage">
                <j-area-linkage v-model="form.areaLinkage" type="cascader" placeholder="请选择您所在省市区"/>
            </a-form-model-item>

            <!-- 详细地址 -->
            <a-form-model-item prop="address">
                <a-textarea v-model="form.address" autocomplete="off"
                            placeholder="详细地址"></a-textarea>
            </a-form-model-item>

            <!-- 注册手机号 -->
            <a-form-model-item prop="mobile">
                <a-input v-model="form.mobile" placeholder="11 位手机号">
                    <a-icon slot="prefix" type="phone" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
            </a-form-model-item>

            <a-row :gutter="16">
                <a-col class="gutter-row" :span="16">
                    <a-form-model-item prop="captcha">
                        <a-input v-model="form.captcha" type="text" placeholder="验证码">
                            <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                        </a-input>
                    </a-form-model-item>
                </a-col>
                <a-col class="gutter-row" :span="8">
                    <a-button
                            class="getCaptcha"
                            :disabled="state.smsSendBtn"
                            @click.stop.prevent="getCaptcha"
                            style="height: 32px;"
                            v-text="!state.smsSendBtn && '获取验证码'||(state.time+' s')"></a-button>
                </a-col>
            </a-row>

            <!-- 登陆密码  -->
            <a-popover placement="rightTop" trigger="click" :visible="state.passwordLevelChecked">
                <template slot="content">
                    <div :style="{ width: '240px' }">
                        <div :class="['user-register', passwordLevelClass]">强度：<span>{{ passwordLevelName }}</span>
                        </div>
                        <a-progress :percent="state.percent" :showInfo="false" :strokeColor=" passwordLevelColor "/>
                        <div style="margin-top: 10px;">
                            <span>请至少输入 8 个字符。请不要使用容易被猜到的密码。</span>
                        </div>
                    </div>
                </template>
                <a-form-model-item prop="password">
                    <a-input-password v-model="form.password" @click="handlePasswordInputClick"
                                      :autocomplete="false"
                                      placeholder="至少8位密码，区分大小写"></a-input-password>
                </a-form-model-item>
            </a-popover>

            <!-- 确认密码 -->
            <a-form-model-item prop="password2">
                <a-input-password v-model="form.password2" autocomplete="false"
                                  placeholder="确认密码"></a-input-password>
            </a-form-model-item>

            <a-form-model-item>
                <a-button type="primary" htmlType="submit" class="register-button" :loading="registerBtn"
                          @click.stop.prevent="handleSubmit" :disabled="registerBtn">注册
                </a-button>
                <router-link class="login" :to="{ name: 'login' }">使用已有账户登录</router-link>
            </a-form-model-item>

        </a-form-model>
    </div>
</template>

<script>
    import { mixinDevice } from '@/utils/mixin.js'
    import { postAction } from '@/api/manage'
    import { checkOnlyUser } from '@/api/api'
    import { getUserRoleListByRoleKeys } from '@/api/user'
    import JAreaLinkage from '@comp/jeecg/JAreaLinkage'
    import JSelectDepart from '@/components/Jane/JSelectDepart'
    import Area from '@/components/_util/Area'
    import { sendSMSForRegister, verifyRegisterSMSCode } from '../../../api/sms'

    const levelNames = {
        0: '低',
        1: '低',
        2: '中',
        3: '强'
    }
    const levelClass = {
        0: 'error',
        1: 'error',
        3: 'success',
        2: 'warning'
    }
    const levelColor = {
        0: '#ff0000',
        1: '#ff0000',
        2: '#ff7e05',
        3: '#52c41a'
    }

    export default {
        name: 'Register',
        components: {
            JAreaLinkage,
            JSelectDepart
        },
        mixins: [mixinDevice],
        data() {

            // 验证密码强度
            let handlePasswordLevel = (rule, value, callback) => {
                let level = 0;
                let reg = /^[0-9a-zA-Z]{6,32}$/;
                if (!reg.test(value)) {
                    callback(new Error('密码输入至少六位字符!'))
                }
                // 判断这个字符串中有没有数字
                if (/[0-9]/.test(value)) {
                    level++
                }
                // 判断字符串中有没有字母
                if (/[a-zA-Z]/.test(value)) {
                    level++
                }
                // 判断字符串中有没有特殊符号
                if (/[^0-9a-zA-Z_]/.test(value)) {
                    level++
                }
                this.state.passwordLevel = level
                this.state.percent = level * 30
                if (level >= 2) {
                    if (level >= 3) {
                        this.state.percent = 100
                    }
                    callback()
                } else {
                    if (level === 0) {
                        this.state.percent = 10
                    }
                    callback(new Error('密码强度不够'))
                }
            }

            // 验证确认密码
            let handlePasswordCheck = (rule, value, callback) => {
                let password = this.form.password
                if (value === undefined) {
                    callback(new Error('请输入密码'))
                }
                if (value && password && value.trim() !== password.trim()) {
                    callback(new Error('两次密码不一致'))
                }
                callback()
            }

            // 验证手机号码格式是否正确、是否已经存在
            let handlePhoneCheck = (rule, value, callback) => {
                let reg = /^1[3456789]\d{9}$/
                if (!reg.test(value)) {
                    callback(new Error('请输入正确手机号'))
                } else {
                    let params = { phone: value }
                    checkOnlyUser(params).then((res) => {
                        if (res.success) {
                            callback()
                        } else {
                            callback('手机号已存在!')
                        }
                    })
                }
            }

            // 验证用户角色
            let checkUserRole = (rule, value, callback) => {
                this.searchParams = {
                    roleIds: value
                }
                // this.form.department = '';
                this.departList = []
                this.showSelectDepart = false
                this.$nextTick(() => {
                    this.showSelectDepart = true
                })
                callback()
            }

            return {
                // 表单验证
                rules: {
                    userRole: [
                        { required: true, message: '请选择用户类型', trigger: 'change' },
                        { validator: checkUserRole, trigger: 'change' }
                    ],
                    password: [{ required: false }, { validator: handlePasswordLevel }],
                    password2: [{ required: false }, { validator: handlePasswordCheck }],
                    mobile: [{ required: false }, { validator: handlePhoneCheck }],
                    captcha: [{ required: true, message: '请输入验证码', trigger: 'change' }],
                    // department: [{ required: true, message: '请选择您所属部门！', trigger: 'change' }],
                    areaLinkage: [{ required: true, message: '请选择您所在区域！', trigger: 'change' }],
                    address: [{ required: true, message: '请输入详细地址！', trigger: 'change' }]
                },

                form: {
                    userRole: undefined, // 用户类型
                    password: '', // 密码
                    password2: '', // 确认密码
                    mobile: '', // 手机号
                    captcha: '', // 验证码，
                    isPrincipal: false,  // 是否是负责人

                    // department: '', // 部门
                    areaLinkage: '贵州省/贵阳市/观山湖区',  // 所属区域
                    address: ''  // 所属区域
                },
                showSelectDepart: true,
                state: {
                    time: 60,
                    smsSendBtn: false,
                    passwordLevel: 0,
                    passwordLevelChecked: false,
                    percent: 10,
                    progressColor: '#FF0000'
                },
                registerBtn: false,

                // 部门表搜索数据
                searchParams: {},

                // 用户类型列表 {label: '',value: ''},
                roleList: [],
                // 单位部门列表 {label: '',value: ''},
                departList: []
            }
        },
        created() {
            this.getDataSource()
        },
        computed: {
            passwordLevelClass() {
                return levelClass[this.state.passwordLevel]
            },
            passwordLevelName() {
                return levelNames[this.state.passwordLevel]
            },
            passwordLevelColor() {
                return levelColor[this.state.passwordLevel]
            }
        },
        methods: {
            foreachList: function(data = []) {
                let arr = []
                data.forEach((item) => {
                    let obj = { label: item['title'], value: item['id'], key: item['id'] }
                    if (item.children && item.children.length) {
                        obj['children'] = this.foreachList(item.children)
                    }
                    arr.push(obj)
                })
                return arr
            },
            // 获取查询的数据源
            getDataSource: async function() {
                let roles = [
                    'hospital', // 医院
                    'clinic', // 诊所
                    'health_room', // 村卫生室
                    'doctor', // 医生
                    'cleaner' // 保洁员
                ]
                let res = await getUserRoleListByRoleKeys({ roleCode: roles.join(',') })
                if (res) {
                    let data = res.result || []
                    let arr = []
                    data.forEach((item) => {
                        arr.push({
                            label: item['roleName'],
                            value: item['id']
                        })
                    })
                    this.roleList = arr
                }
            },

            handlePasswordInputClick() {
                if (!this.isMobile()) {
                    this.state.passwordLevelChecked = true
                    return
                }
                this.state.passwordLevelChecked = false
            },

            // 提交注册信息
            handleSubmit: async function(e) {
                e.preventDefault()

                let values = this.form
                let data = {
                    username: values.mobile,
                    realname: values.mobile,
                    password: values.password,
                    phone: values.mobile,
                    smscode: values.captcha,
                    // departIds: values.department,
                    relTenantIds: values.userRole,
                    address: values.address,
                    isPrincipal: values.isPrincipal ? 1 : 0,  // 是否是部门负责人
                    jsonObject: JSON.stringify({ username: values.mobile, password: values.password })
                }

                if (!await this.verifySMSCode()) {
                    return
                }

                let areaData = new Area()
                let arrID = await areaData.getRealCode(values.areaLinkage)
                let arrText = await areaData.getText(values.areaLinkage).split('/')

                // 省份
                if (arrID[0] && arrText[0]) {
                    data['provinceCode'] = arrID[0]
                    data['province'] = arrText[0]
                }
                // 城市
                if (arrID[1] && arrText[1]) {
                    data['cityCode'] = arrID[1]
                    data['city'] = arrText[1]
                }
                // 区域
                if (arrID[2] && arrText[2]) {
                    data['areaCode'] = arrID[2]
                    data['area'] = arrText[2]
                }

                let valid = await this.$refs['ruleForm'].validate()
                // return ;
                if (valid) {
                    let res = await postAction('/sys/user/register', data)
                    if (!res.success) {
                        this.registerFailed(res.message)
                    } else {
                        this.$router.push({ name: 'registerResult', params: { ...values } })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            },

            // 验证短信验证码是否正确
            verifySMSCode: async function() {
                let params = {
                    phone: this.form.mobile,
                    smscode: this.form.captcha,
                }
                let res = await verifyRegisterSMSCode(params)
                if (res && res.success) {
                    this.$message.success(res.message || `验证通过`)
                    return true
                } else {
                    this.$message.error(res.message || `验证失败`)
                    return false
                }
            },
            // 获取验证码
            getCaptcha(e) {
                e.preventDefault()
                let that = this

                this.$refs['ruleForm'].validateField(['mobile'], { force: true }, (err, values) => {
                        if (!err) {
                            this.state.smsSendBtn = true
                            let interval = window.setInterval(() => {
                                if (that.state.time-- <= 0) {
                                    that.state.time = 60
                                    that.state.smsSendBtn = false
                                    window.clearInterval(interval)
                                }
                            }, 1000)
                            const hide = this.$message.loading('验证码发送中..', 0)
                            const params = {
                                phone: that.form.mobile,
                                type : 1, // 注册
                            };
                            sendSMSForRegister(params).then((res) => {
                                if (!res.success) {
                                    this.registerFailed(res.message)
                                    setTimeout(hide, 0)
                                }
                                setTimeout(hide, 500)
                            }).catch(err => {
                                setTimeout(hide, 1)
                                clearInterval(interval)
                                that.state.time = 60
                                that.state.smsSendBtn = false
                                this.requestFailed(err)
                            })
                        }
                    }
                )
            },
            registerFailed(message) {
                this.$notification['error']({
                    message: '注册失败',
                    description: message,
                    duration: 2
                })
            },
            requestFailed(err) {
                this.$notification['error']({
                    message: '错误',
                    description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
                    duration: 4
                })
                this.registerBtn = false
            }
        },
        watch: {
            'state.passwordLevel'(val) {
                console.log(val)
            }
        }
    }
</script>
<style lang="less">
    .user-register {

        &.error {
            color: #ff0000;
        }

        &.warning {
            color: #ff7e05;
        }

        &.success {
            color: #52c41a;
        }

    }

    .user-layout-register {
        .ant-input-group-addon:first-child {
            background-color: #fff;
        }
    }
</style>
<style lang="less" scoped>
    .user-layout-register {

        & > h3 {
            font-size: 16px;
            margin-bottom: 20px;
        }

        .getCaptcha {
            display: block;
            width: 100%;
            height: 40px;
        }

        .register-button {
            width: 50%;
        }

        .login {
            float: right;
            line-height: 40px;
        }
    }

    .ant-form-item {
        margin-bottom: 8px !important;
    }
</style>
